package activitys;

import io.web.JSONConnector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import user.Base;
import user.BaseUpgrade;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import misc.BasewarsConfig;
import nl.preflag.basewars.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;

/**
 * @author Patrick van Gils, 0787862 INF3M
 * Activity is called when a user wants to attack or upgrade a base.
 */

public class BaseActionActivity extends Activity implements LocationListener {
	
	int base_id, player_id, base_type, ATTACK_BASE, UPGRADE_TYPE;
	String USER_ID, temp;
	double lat, lng;
	Spinner inrangeSpinner, upgradeSpinner;
	ImageButton actionMapButton, attackButton, upgradeButton;
	JSONConnector webby;
	JSONArray inrangeListJson, upgradeListJson;
	HashMap<String, String> map, o;
	List<Overlay> mapOverlays;
	MapView mapView;
	List<HashMap<String, String>> fillMaps;
	Base myBases[]; // Bases in range in spinner
	BaseUpgrade myUpgrades[]; // Upgrade types in spinner
	JSONObject JSONResponse;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);

        Bundle extras = getIntent().getExtras();        
        base_id = extras.getInt("base_id");
        player_id = extras.getInt("player_id");
        base_type = extras.getInt("base_type");
        
        SharedPreferences pref = getSharedPreferences("programSettings", MODE_PRIVATE);
        USER_ID = pref.getString("userId", null);
        
        // Type of base_type determins which layout is being loaded
        switch(base_type) {
        case 1:
        		setContentView(R.layout.base_action_upgrade);
        		findViews();
        		fillUpgradeTypes();
        	break;
        case 2:
        		setContentView(R.layout.base_action_upgrade);
        		findViews();
        		fillUpgradeTypes();
        	break;
        case 3:
        		setContentView(R.layout.base_action_attack);
        		findViews();
        		fillMyBases();
        	break;
        }
    }
	
	/**
	 * Find the views
	 */
	private void findViews() {
		switch(base_type) {
        case 1:
	    		upgradeButton = (ImageButton) findViewById(R.id.actionUpgradeButton);
	    		upgradeSpinner = (Spinner) findViewById(R.id.actionUpgradeTypeSpinner);
	    		upgradeButton.setOnClickListener(new View.OnClickListener() {
	    			public void onClick(View v) {
	    				upgradeBase();
	    			}
	    		});
        	break;
        case 2:
        		upgradeButton = (ImageButton) findViewById(R.id.actionUpgradeButton);
        		upgradeSpinner = (Spinner) findViewById(R.id.actionUpgradeTypeSpinner);
        		upgradeButton.setOnClickListener(new View.OnClickListener() {
        			public void onClick(View v) {
        				upgradeBase();
        			}
        		});
        	break;
        case 3:
        		inrangeSpinner = (Spinner) findViewById(R.id.actionInrageBasesSpinner);
        		attackButton = (ImageButton) findViewById(R.id.actionAttackButton);
        		
        		attackButton.setOnClickListener(new View.OnClickListener() {
        			public void onClick(View v) {
        				attackBase();
        			}
        		});
        	break;
        }
		
		actionMapButton = (ImageButton) findViewById(R.id.actionMapFriendButton);
		actionMapButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	/**
	 * Fill the spinner with your bases that are in range to attack the selected enemy base
	 */
	private void fillMyBases() {
		
		fillMaps = new ArrayList<HashMap<String, String>>();
    	try 
    	{
    		webby = new JSONConnector();
    		inrangeListJson = webby.connect("basesinrange/"+USER_ID+"/"+base_id+"", "result", false);
    		myBases = new Base[inrangeListJson.length()];
    		for(int i=0;i<inrangeListJson.length();i++) 
    		{
    			map = new HashMap<String, String>();	
    			JSONObject e = inrangeListJson.getJSONObject(i);
    			
    			myBases[i] = new Base(e.getInt("id"),e.getInt("player_id"),e.getDouble("loc_longitude"), e.getDouble("loc_latitude"), e.getInt("health"), e.getString("name"), e.getString("description"));
    			
    			map.put("id",  ""+e.getInt("id"));
    	    	map.put("player_id", ""+e.getInt("player_id"));
    	    	map.put("loc_longitude", ""+e.getDouble("loc_longitude"));
    	    	map.put("loc_latitude", ""+e.getDouble("loc_latitude"));
    	    	map.put("health", ""+e.getInt("health"));
    	    	map.put("name", ""+e.getString("name"));
    	    	map.put("description", ""+e.getString("description"));
    	    	fillMaps.add(map);	

    		}
    		ArrayAdapter<Base> adapter = new ArrayAdapter<Base>( this, android.R.layout.simple_spinner_item, myBases );
    		adapter.setDropDownViewResource(
    	            android.R.layout.simple_spinner_dropdown_item);
    		inrangeSpinner.setAdapter(adapter);
    		inrangeSpinner.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        	// set selected base id as ATTACK_BASE (id)
                        	Base d = myBases[position];
                        	ATTACK_BASE = d.getId();
                        }
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    }
                );
    		
	   	} catch (Exception e) 
	   	{
	   		e.printStackTrace();
	   	}
	}
	
	/**
	 * Fill the spinner with the upgrade types
	 */
	private void fillUpgradeTypes() {
		
		fillMaps = new ArrayList<HashMap<String, String>>();
    	try 
    	{
    		webby = new JSONConnector();
    		upgradeListJson = webby.connect("UpgradeType", "result", false);
    		myUpgrades = new BaseUpgrade[upgradeListJson.length()];
    		for(int i=0;i<upgradeListJson.length();i++) 
    		{
    			map = new HashMap<String, String>();	
    			JSONObject e = upgradeListJson.getJSONObject(i);
    			
    			myUpgrades[i] = new BaseUpgrade(e.getInt("id"), e.getString("name"));
    			
    			map.put("id",  ""+e.getInt("id"));
    	    	map.put("name", ""+e.getString("name"));
    	    	fillMaps.add(map);	

    		}
    		ArrayAdapter<BaseUpgrade> adapter = new ArrayAdapter<BaseUpgrade>( this, android.R.layout.simple_spinner_item, myUpgrades );
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    		upgradeSpinner.setAdapter(adapter);
    		upgradeSpinner.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        	// set selected upgrade type as UPGRADE_TYPE
                        	BaseUpgrade d = myUpgrades[position];
                        	UPGRADE_TYPE = d.getId();
                        }
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    }
                );
    		
	   	} catch (Exception e) 
	   	{
	   		e.printStackTrace();
	   	}	
	}
	
	/**
	 * Attack base
	 */
	private void attackBase() {
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("base_attack", ""+ATTACK_BASE));
        nameValuePairs.add(new BasicNameValuePair("base_defend", ""+base_id));
        // Webservice
        try 
    	{
            webby = new JSONConnector();
            webby.setBaseUrl(BasewarsConfig.getApiBaseUrl());
            JSONResponse = webby.requestPostObject("/battle", nameValuePairs);
        	if (JSONResponse.getString("success").equals("false")) {
	         	final AlertDialog ad = new AlertDialog.Builder(BaseActionActivity.this).create();
		       		 ad.setTitle("Battle error");
		       		 ad.setMessage(JSONResponse.getString("error"));
		       		 ad.setButton("OK", new DialogInterface.OnClickListener() {
		       			 public void onClick(DialogInterface dialog, int which) {
		       				 ad.dismiss();  
		       				 
		       			 }
		       		 }); 
		       	 ad.show();
	       	} else {
	       		finish();
	       	}
    	} 
        catch (Exception e) 
	   	{
        	 e.printStackTrace();
	   	}
	}
	
	/**
	 * Upgrade a base
	 */
	private void upgradeBase() {
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("base_id", ""+base_id));
        nameValuePairs.add(new BasicNameValuePair("upgradetype_id", ""+UPGRADE_TYPE));
        nameValuePairs.add(new BasicNameValuePair("lat", ""+lat));
        nameValuePairs.add(new BasicNameValuePair("lon", ""+lng));
        // Webservice
        try 
    	{
	        webby = new JSONConnector();
	        webby.setBaseUrl(BasewarsConfig.getApiBaseUrl());
	        JSONResponse = webby.requestPostObject("/upgrade", nameValuePairs);
	        if (JSONResponse.getString("success").equals("false")) {
	         	final AlertDialog ad = new AlertDialog.Builder(BaseActionActivity.this).create();
	         		 ad.setTitle("Upgrade error");
	         		 ad.setMessage(JSONResponse.getString("error"));
		       		 ad.setButton("OK", new DialogInterface.OnClickListener() {
		       			 public void onClick(DialogInterface dialog, int which) {
		       				 ad.dismiss();
		       			 }
		       		 }); 
		       	 ad.show();
	       	} else {
	       		finish();
	       	}
    	}
        catch (Exception e) 
	   	{
        	 e.printStackTrace();
	   	}
	}

	@Override
	public void onLocationChanged(Location location) {
		// update lat and lng with GPS information
		if (location != null) {
			lat = location.getLatitude();
			lng = location.getLongitude();
	    }
	}

	@Override
	public void onProviderDisabled(String arg0) {
		final AlertDialog ad = new AlertDialog.Builder(BaseActionActivity.this).create();
		 ad.setTitle("GPS off");
		 ad.setMessage("Certain options are not available when the GPS is turned off.");
		 ad.setButton("OK", new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int which) {
				 ad.dismiss();  
			 }
		 }); 
		 ad.show();
			switch(base_type) {
	        case 1:
		    		upgradeButton.setVisibility(View.GONE);
	        	break;
	        case 2:
	        		upgradeButton.setVisibility(View.GONE);
	        	break;
	        }
	}

	@Override
	public void onProviderEnabled(String provider) {
		switch(base_type) {
        case 1:
	    		upgradeButton.setVisibility(View.VISIBLE);
        	break;
        case 2:
        		upgradeButton.setVisibility(View.VISIBLE);
        	break;
        }
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
